<template>
    <div>
    <div class="Add">
      <a-button type="primary" ghost @click="Add">添加维修工</a-button>
      <a-button type="primary" ghost @click="isRowSelection = !isRowSelection">选择多行</a-button>
      <a-button v-if="isRowSelection" danger>删除</a-button>
      <a-popconfirm title="你确定要导出吗 ?" ok-text="是" cancel-text="否" @confirm="confirm"
        @cancel="cancel1">
        <a-button v-if="isRowSelection">导出为Excel</a-button>
      </a-popconfirm>
    </div>
    <a-table :columns="columns" :data-source="dataSource" :row-selection="isRowSelection ? rowSelection : null"
      bordered>
      <template #bodyCell="{ column, text, record }">
        <template v-if="['name', 'age', 'address'].includes(column.dataIndex)">
          <div>
            <a-input v-if="editableData[record.key]" v-model:value="editableData[record.key][column.dataIndex]"
              style="margin: -5px 0" />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.key]">
              <a-typography-link @click="save(record.key)">保存</a-typography-link>
              <a-popconfirm title="确认取消保存吗?" cancelText="不确定" okText="确定" @confirm="cancel(record.key)">
                <a>取消保存</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.key)">编辑</a>
              <a @click="Udelete(record)">删除</a>
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
  <a-modal v-model:open="open" title="添加维修工" :confirm-loading="confirmLoading" @ok="handleOk" cancelText="取消"
    okText="提交">
    <p>{{ modalText }}</p>
  </a-modal>
</template>

<script setup>
import Table from 'ant-design-vue/es/table/Table';
import { reactive, ref, computed, unref } from 'vue';
import { cloneDeep } from 'lodash-es';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { createVNode } from 'vue';
import { Modal } from 'ant-design-vue';
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus';
const isRowSelection = ref(false)
const modalText = ref('');
const open = ref(false);
const confirmLoading = ref(false);
const selectedRowKeys = ref([]);
const selectedRowList = ref([]);
const columns = [
  {
    title: 'name',
    dataIndex: 'name',
    width: '25%',
  },
  {
    title: 'age',
    dataIndex: 'age',
    width: '15%',
  },
  {
    title: 'address',
    dataIndex: 'address',
    width: '40%',
  },
  {
    title: '操作',
    dataIndex: 'operation',
  },
];
const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
  });
}
const dataSource = ref(data);
const editableData = reactive({});

const edit = key => {
  editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
};
const Udelete = key => {
  // dataSource.value = dataSource.value.filter(item => item.key !== key);
  Modal.confirm({
    title: '你确定要删除这个账号吗?',
    icon: createVNode(ExclamationCircleOutlined),
    content: `账号名:${key.name}`,
    okText: 'Yes',
    okType: 'danger',
    cancelText: 'No',
    onOk() {
      // console.log('删除');
    },
    onCancel() {
      // console.log('取消删除');
    },
  });
};
const save = key => {
  Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
  delete editableData[key];
};
const cancel = key => {
  delete editableData[key];
};
const Add = () => {
  open.value = true;
}
const handleOk = () => {
  modalText.value = '提交中.......';
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
    modalText.value = '';
  }, 2000);
};
const rowSelection = computed(() => {
  return {
    selectedRowKeys: unref(selectedRowKeys),
    onChange: onSelectChange,
    hideDefaultSelections: true,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: '选择偶数行',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_key, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          selectedRowKeys.value = newSelectedRowKeys;
          // console.log(selectedRowKeys.value);
        },
      },
      {
        key: 'even',
        text: '选择奇数行',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_key, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          selectedRowKeys.value = newSelectedRowKeys;
          // console.log(selectedRowKeys.value);
        },
      },
    ],
  };
});
const onSelectChange = (changableRowKeys, selectedRows) => {
  // console.log('selectedRowKeys changed: ', changableRowKeys, selectedRows);
  selectedRowKeys.value = changableRowKeys;
  selectedRowList.value = selectedRows
};
const exportBtn = () => {
  if (selectedRowList.value.length == 0) {
    ElMessage({
      message: '不可以导出空的Excel哦',
      type: 'error',
    })
    return;
  }
  const dataToExport = selectedRowList.value.map(row => {
    return {
      Name: row.name,
      Age: row.age,
      Address: row.address
    };
  });
  const worksheet = XLSX.utils.json_to_sheet(dataToExport);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  XLSX.writeFile(workbook, '表格数据.xlsx');
};

const confirm = () => {
  exportBtn()
};
const cancel1 = () => {
  // console.log(e);
  ElMessage({
      message: '取消导出为Excel',
      type: 'warning',
    })
};
</script>

<style scoped>
.Add {
  display: flex;
  align-items: center;
  height: 70px;
  gap: 10px;
  padding: 0 10px;
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>